package com.lsq.baseadmin.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author jam 2019/12/28 11:53
 * @desc
 */
public class AliyunOssUtil {

    private static final String ENDPOINT = "http://oss-cn-beijing.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "???";
    private static final String ACCESS_KEY_SECRET = "???";
    private static final String BUCKET_NAME = "???";
    private static final String URL = "http://???.oss-cn-beijing.aliyuncs.com/";


    /**
     *
     * @param imgFile 上传的文件
     * @param dir 文件所属的文件夹
     * @return url
     */
    public static String upload(MultipartFile imgFile, String dir) throws IOException{
        String fileName = imgFile.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));

        String url = URL;

        String newName = UUID.randomUUID().toString().replace("-","") + fileType;
        //云端存放的文件夹
        String objectName = newName;

        if (StringUtils.hasText(dir)) {
            url = url + dir + "/";
            objectName = dir + "/" + newName;
        }
        url = url  + newName;

        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        InputStream is = imgFile.getInputStream();
        ossClient.putObject(BUCKET_NAME, objectName, is);
        return url;
    }

    /**
     * 上传枚举js
     * @param is InputStream
     */
    public static void uploadEnumJs(InputStream is){
//        String url = "http://base-admin.oss-cn-beijing.aliyuncs.com/js/publicEnums.js";
        //云端存放的文件夹
        String objectName = "js/publicEnums.js";
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        ossClient.putObject(BUCKET_NAME, objectName, is);
    }
}
